//////// FIKASHELL NAMESPACE

var FikaShell = {};

FikaShell.log = function(msg) {
  if (typeof(console) != "undefined") {
    console.log(msg); // appears in Firebug debugger
  }
  else {
    alert(msg);
  }
};

FikaShell.clearInput = function() {
  $('#shell-input')[0].value = "";
};

FikaShell.clearOutput = function() {
  $('#shell-results')[0].value = "";
};

FikaShell.appendToResults = function(s) {
  $("#shell-results")[0].value += s;
  $("#shell-results")[0].scrollTop = $("#shell-results")[0].scrollHeight - $("#shell-results")[0].clientHeight;
};

FikaShell.appendWithNewLine = function(s) {
  FikaShell.appendToResults(s + "\n");
};

FikaShell.enter = function(s) {  
  FikaShell.appendToResults("> " + s + "\n");
  if (!FikaShell.executeFlags(s)) {
    FikaShell.fika.exec(s);
  }
  if (FikaShell.isDisplayingStackTrace) {
    FikaShell.appendToResults("Stack: " + FikaShell.stack.toString() + "\n");
  }
};

// Returns true if any flags were executed
FikaShell.executeFlags = function(s) {
  switch (s) {
    case (":trace"):
      FikaShell.isDisplayingStackTrace = !(FikaShell.isDisplayingStackTrace);
      if (FikaShell.isDisplayingStackTrace) {
        FikaShell.appendWithNewLine("Stack tracing enabled");
      }
      else {
        FikaShell.appendWithNewLine("Stack tracing disabled");        
      }
      return true;
    case (":clear"):
        FikaShell.clearOutput();
        return true;
    case (":names"):
      FikaShell.appendWithNewLine(FikaShell.names.toString());
      return true;
    default:
      return false;
  }
};

// These must be last
FikaShell.stack = new RuntimeStack();
FikaShell.names = new SymbolTable();
FikaShell.fika = new Fika(FikaShell.stack, FikaShell.names, FikaShell.appendWithNewLine);
FikaShell.isDisplayingStackTrace = false;

//////// JQUERY EVENTS

$(document).ready(function() {
  
  $("#version").html(FikaShell.fika.getVersionInfo() + "<br />Author: " + FikaShell.fika.getAuthorInfo());
  FikaShell.clearInput();
  FikaShell.clearOutput();
 
  $('#shell-input').keypress(function (e) {
    if (e.which == 13 || e.which == 10) {
      FikaShell.enter(e.target.value);
      FikaShell.clearInput();
    }
    /*else {
      $("#debugging").text("e.which);
    }*/
  });

});